package ecs.net.systems;

import ecs.core.BaseSystem;
import ecs.net.Status;
import ecs.net.components.AddressComponent;
import ecs.net.components.ServerSocketComponent;
import ecs.net.components.StatusComponent;

import java.io.IOException;
import java.net.ServerSocket;

public class ServerInitSystem extends BaseSystem {

    public ServerInitSystem()
    {
        super();
        interestingComponentTypes(new Class[]{AddressComponent.class, ServerSocketComponent.class
                , StatusComponent.class});
    }

    public void init()
    {
        entityComponents().forEach(components -> {
            AddressComponent address = (AddressComponent) components.get(0);
            ServerSocketComponent serverSocket = (ServerSocketComponent) components.get(1);
            StatusComponent status = (StatusComponent) components.get(2);
            if(serverSocket.socket() == null)
            {
                try {
                    ServerSocket socket = new ServerSocket(address.port());
                    serverSocket.socket(socket);
                    status.status(Status.Listened);
                } catch (IOException e) {
//                    status.status(Status.Closed);

                }
            }
        });
    }
}
